const { ccclass, property } = cc._decorator;

@ccclass
export default class FishManager {

    fishPool: cc.NodePool = null;

    prefabCache: Map<string, cc.Prefab> = new Map<string, cc.Prefab>();

    fishpath: any[] = [];

    constructor() {
        this.fishPool = new cc.NodePool("FishCtr")
        this.initTestPath()
    }

    initTestPath() {
        let newObj: { [k: string]: any } = {};
        newObj.test_1 = [cc.v3(-765, -97, 0), cc.v3(-265, -26, 0), cc.v3(66, -87, 0), cc.v3(453, -59, 0), cc.v3(661, 113, 0)]
        newObj.test_2 = [cc.v3(700, 90, 0),  cc.v3(-700, 113, 0)]
        newObj.test_3 = [cc.v3(-765, -297, 0), cc.v3(-265, -26, 0), cc.v3(66, -87, 0), cc.v3(453, -59, 0), cc.v3(661, 113, 0)]
        newObj.test_4 = [cc.v3(700, -10, 0), cc.v3(-700, 213, 0)]
        newObj.test_5 = [cc.v3(-765, -497, 0), cc.v3(-265, -26, 0), cc.v3(66, -87, 0), cc.v3(453, -59, 0), cc.v3(661, 113, 0)]
        newObj.test_6 = [cc.v3(750, 97, 0),  cc.v3(-761, 313, 0)]
        newObj.test_7 = [cc.v3(-765, 197, 0), cc.v3(-265, -26, 0), cc.v3(66, -87, 0), cc.v3(453, -59, 0), cc.v3(661, 113, 0)]
        newObj.test_8 = [cc.v3(-765, 200, 0), cc.v3(561, 383, 0)]
        newObj.test_9 = [cc.v3(-765, 397, 0), cc.v3(-265, -26, 0), cc.v3(66, -87, 0), cc.v3(453, -59, 0), cc.v3(661, 113, 0)]
        newObj.test_10 = [cc.v3(700, 497, 0),  cc.v3(-700, 10, 0)]
        for (let i = 1; i < 11; i++) {
            this.fishpath.push(newObj['test_' + i])
        }
    }

    getFishPath(){
        let index =Math.floor(Math.random()*10)
        let [...arr] = this.fishpath[index];
        // arr.push(0) //添加新项保证不会修改原始数组
        // arr.pop()
        return arr
    }

    public putFish(fish: cc.Node) {
        console.log('回收鱼')
        this.fishPool.put(fish)
    }

    /**
     * 
     * @param type 预制体路径
     * @returns cc.Prefab
     */
    async getFishPrefab(type: string): Promise<cc.Prefab> {
        // 在这里动态生成子弹
        return new Promise(resolve => {
            if (this.prefabCache.has(type)) {
                resolve(this.prefabCache.get(type))
                return
            }
            cc.resources.load(type, cc.Prefab, (err, fab: cc.Prefab) => {
                if (err) {
                    resolve(null)
                    return console.log('鱼加载错误 ', err)
                }
                this.prefabCache.set(type, fab)
                fab.addRef()
                resolve(fab)
            })
        })
    }

    async getFishByType(type: string): Promise<cc.Node> {
        //在这里动态生成子弹
        if (this.fishPool.size() > 0) {
            return this.fishPool.get()
        }
        let fab = await this.getFishPrefab(type)
        let fish = cc.instantiate(fab)
        return fish
    }

    clearCache() {
        this.prefabCache.forEach((value, key) => {
            value.decRef()
        })
    }
}
export const fishManager = new FishManager()